<template>
  <div class="ai-assistant-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">智能客服管理</h2>
        <p class="page-subtitle">创建和管理您的AI客服助手</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="openCreateDialog">
          <el-icon><Plus /></el-icon>
          创建智能客服
        </el-button>
      </div>
    </div>

    <!-- 智能体列表区域 -->
    <div class="agent-list-area">
      <el-empty v-if="agents.length === 0" description="暂无智能客服，请创建" />
      <div v-else class="agent-cards">
        <el-card v-for="agent in agents" :key="agent.id" class="agent-card">
          <div class="agent-card-header">
            <img v-if="agent.avatar" :src="agent.avatar" class="agent-avatar" />
            <el-icon v-else><User /></el-icon>
            <h3>{{ agent.name }}</h3>
          </div>
          <div class="agent-card-body">
            <p>{{ agent.welcomeMessage }}</p>
            <p>专业领域: {{ getDomainText(agent.domains) }}</p>
          </div>
          <div class="agent-card-actions">
            <el-button type="text" @click="editAgent(agent)">编辑</el-button>
            <el-button type="text" @click="deleteAgent(agent.id)">删除</el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 智能客服配置弹窗 -->
    <CreateAssistantDialog
      v-model="dialogVisible"
      @saved="handleAssistantSaved"
    />

    <!-- 底部统计信息 -->
    <div class="stats-panel">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ stats.totalUsers }}</h3>
                <p>总用户数</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><ChatDotRound /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ stats.totalMessages }}</h3>
                <p>总消息数</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ stats.avgResponseTime }}s</h3>
                <p>平均响应时间</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Star /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ stats.satisfactionRate }}%</h3>
                <p>满意度</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import {
  Setting,
  Check,
  Plus,
  ChatDotRound,
  Promotion,
  User,
  Clock,
  Star,
  InfoFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import CreateAssistantDialog from '@/components/CreateAssistantDialog.vue'

// 智能体列表
const agents = ref([])

// 弹窗可见性
const dialogVisible = ref(false)


// 统计数据
const stats = reactive({
  totalUsers: 0,
  totalMessages: 0,
  avgResponseTime: 0,
  satisfactionRate: 0,
  totalAssistants: 0
})

// 知识库列表
const knowledgeBases = ref([])

// 获取专业领域文本
const getDomainText = (domains) => {
  const domainMap = {
    medical: '医疗咨询',
    appointment: '预约挂号',
    health: '健康管理',
    diagnosis: '疾病诊断',
    medication: '用药指导'
  }
  return domains.map(d => domainMap[d]).join('、')
}

// 加载智能体列表
const loadAgents = async () => {
  try {
    const response = await api.get('/api/assistants')
    agents.value = response.data
  } catch (error) {
    console.error('加载智能客服失败:', error)
    ElMessage.error('加载智能客服失败')
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await api.get('/api/assistants/stats')
    Object.assign(stats, response.data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  }
}

// 加载知识库列表
const loadKnowledgeBases = async () => {
  try {
    const response = await api.get('/api/knowledge/bases')
    knowledgeBases.value = response.data
  } catch (error) {
    console.error('加载知识库列表失败:', error)
    ElMessage.error('加载知识库列表失败')
  }
}

// 打开创建智能客服弹窗
const openCreateDialog = () => {
  dialogVisible.value = true
}

// 处理助理保存
const handleAssistantSaved = async (assistantData) => {
  try {
    // 这里应该调用API保存助理数据
    // await axios.post('/api/assistants', assistantData)
    
    // 模拟保存成功，刷新列表
    await loadAgents()
    await loadStats()
    ElMessage.success('智能客服创建成功！')
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  }
}

// 编辑智能体
const editAgent = (agent) => {
  // TODO: 实现编辑功能
  ElMessage.info('编辑功能开发中...')
}

// 删除智能体
const deleteAgent = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此智能客服吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await api.delete(`/api/assistants/${id}`)
    ElMessage.success('智能客服删除成功！')
    await loadAgents()
    await loadStats()
  } catch {
    ElMessage.info('已取消删除')
  }
}


onMounted(() => {
  loadAgents()
  loadStats()
  loadKnowledgeBases()
})

onUnmounted(() => {
  console.log('AIAssistant component unmounted');
});
</script>

<style scoped>
.ai-assistant-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0 0 5px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 智能体列表区域 */
.agent-list-area {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 300px; /* 确保有足够的空间 */
  max-height: 60vh;
  overflow-y: auto;
}

.agent-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  width: 100%;
  align-items: flex-start;
}

.agent-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.agent-card-header {
  display: flex;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.agent-card-header .agent-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.agent-card-header .el-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 15px;
  background: #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 20px;
}

.agent-card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.agent-card-body {
  padding: 15px;
  min-height: 80px;
}

.agent-card-body p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.agent-card-body p:last-child {
  margin-bottom: 0;
}

.agent-card-actions {
  padding: 10px 15px;
  border-top: 1px solid #e4e7ed;
  text-align: right;
}

.agent-card-actions .el-button {
  margin-left: 10px;
}


/* 配置面板（在弹窗内） */
.config-form {
  padding: 10px 0;
}

/* 头像上传 */
.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 6px;
}

/* 底部统计信息 */
.stats-panel {
  margin-top: auto;
}

.stat-card {
  text-align: center;
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-info h3 {
  margin: 0 0 5px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stat-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .agent-cards {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .ai-assistant-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .stats-panel .el-col {
    margin-bottom: 10px;
  }

  .agent-cards {
    grid-template-columns: 1fr; /* 在小屏幕上单列显示 */
  }
}
</style> 